<template>
  <div class="main">
    <el-descriptions title="谷歌令牌设置" :column="2">
      <el-descriptions-item label="状态">
        <el-tag :type="enabled ? 'success' : 'danger'">
          {{ enabled ? "已启用" : "未启用" }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="操作">
        <el-button type="success" @click="firstStep">启用</el-button>
        <el-button type="danger" @click="disableTotp">禁用</el-button>
      </el-descriptions-item>
    </el-descriptions>
    <ConfigDialog ref="configDialog" :refresh="queryStatus" />
    <DisabledDialog ref="disabledDialog" :refresh="queryStatus" />
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import {
  beginSetup,
  getQrCode,
  enableTotp,
  getTotpStatus
} from "@/api/totpApi";
import ConfigDialog from "./comppnents/ConfigDialog.vue";
import DisabledDialog from "./comppnents/DisabledDialog.vue";

const configDialog = ref(null);
const disabledDialog = ref(null);
const enabled = ref(false);
const queryStatus = async () => {
  const { data } = await getTotpStatus();
  enabled.value = data.enabled;
};
const disableTotp = () => {
  disabledDialog.value?.open();
};
const firstStep = async () => {
  try {
    const { data } = await beginSetup();
    const { setupId } = data;
    if (setupId) {
      const { data: urlData } = await getQrCode({ setupId });
      if (urlData instanceof Blob) {
        const url = URL.createObjectURL(urlData);
        configDialog.value?.open({ url, setupId });
      }
    }
  } catch (e) {
    console.log(e);
  }
};
queryStatus();
</script>
<style scoped>
.main {
  padding: 20px;
  background-color: #fff;
}
</style>
